package com.namuan.jp_stock.activity;



import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import com.namuan.jp_stock.object.ShotActivity;
import com.namuan.jp_stock.util.ActivityItemAdapter;
import com.namuan.jp_stock.util.AsyncJustplaceRunner;
import com.namuan.jp_stock.util.BaseRequestListener;
import com.namuan.jp_stock.util.ImageManager;
import com.namuan.jp_stock.util.Justplace;
import com.namuan.jp_stock.util.JustplaceError;
import com.namuan.jp_stock.util.ObjUtils;
import com.namuan.jp_stock.util.PointImageView;
import com.namuan.jp_stock.util.SessionStore;
import com.namuan.jp_stock.util.Util;
import com.namuan.jp_stock.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class UserProfileActivity extends Activity implements OnClickListener,
OnItemClickListener, RadioGroup.OnCheckedChangeListener {

	
	private Activity mActivity;

	private ArrayList<ShotActivity> activityItems;
	
	private ListView activityListView;
	private ActivityItemAdapter aa;
	
	private TextView tvHasItem;
	private Justplace mJustplace;
	private AsyncJustplaceRunner mAsyncRunner;
	private ImageButton imgBtnAddFriend;
	private ImageView navBtn1;
	private ImageView navBtn2;
	private ImageView navBtn3;
	private ImageView navBtn4;
	private PointImageView userImg;
	private TextView userRankingText;
	private TextView userExpText;
	private TextView userProfileBioText;
	private TextView userNickText;
	private String userRanking;
	private String userExp;
	private String userMayor;
	private String strUserImg;
	private String userBio;
	private String usernickname;
	
	
	private String usernick;
	private String loginnick;
	private boolean isfriend;
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.userprofile);
		LoginActivity.activityList.add(this);
		
		mActivity = this;
		
		usernick = this.getIntent().getExtras().getString("usernick");
		
		ImageButton headerWriteBtn = (ImageButton) findViewById(R.id.headerWriteBtn);
		TextView userHeaderNickname = (TextView) findViewById(R.id.userHeaderNickname);
		
		activityListView = (ListView) findViewById(R.id.activityListView);
		tvHasItem = (TextView) findViewById(R.id.tvHasItem);
		imgBtnAddFriend = (ImageButton) findViewById(R.id.imgBtnAddFriend);
		imgBtnAddFriend.setOnClickListener(this);
		
		userRankingText = (TextView) findViewById(R.id.userRankingText);
		userExpText = (TextView) findViewById(R.id.userExpText);
		
		navBtn1 = (ImageView) findViewById(R.id.navBtn1);
		navBtn2 = (ImageView) findViewById(R.id.navBtn2);
		navBtn3 = (ImageView) findViewById(R.id.navBtn3);
		navBtn4 = (ImageView) findViewById(R.id.navBtn4);


		navBtn2.setImageResource(R.drawable.stockline_nor);
		navBtn3.setImageResource(R.drawable.friendsline_nor);
		navBtn4.setImageResource(R.drawable.profile_nor);
		/*
		navBtn2.setBackgroundResource(R.drawable.search_nor);
		navBtn3.setBackgroundResource(R.drawable.news_nor);
		navBtn4.setBackgroundResource(R.drawable.setting_nor);*/
		headerWriteBtn.setOnClickListener(this);

		//activityUserImg = (PointImageView) findViewById(R.id.activityUserImg);
		userImg = (PointImageView) findViewById(R.id.userImg);

		userProfileBioText = (TextView) findViewById(R.id.userProfileBioText);
		userNickText = (TextView) findViewById(R.id.userProfileNickText);

		userHeaderNickname.setOnClickListener(this);
		navBtn1.setOnClickListener(this);
		navBtn2.setOnClickListener(this);
		navBtn3.setOnClickListener(this);
		navBtn4.setOnClickListener(this);

		
		headerWriteBtn.setOnClickListener(this);
		
		
		activityItems = new ArrayList<ShotActivity>();
		aa = new ActivityItemAdapter(this, R.layout.activity_list_row,
				activityItems);
		
		
		mJustplace = new Justplace();
		SessionStore.restore(mJustplace, this);
		mJustplace.setHeader(userHeaderNickname);
		mAsyncRunner = new AsyncJustplaceRunner(mJustplace);
		init();
	}
	
	
	private void init() {

		Bundle params = new Bundle();
		loginnick = mJustplace.getmUserNickname();
		
		Bundle userparams = new Bundle();
		userparams.putString("mynick", mJustplace.getmUserNickname());
		userparams.putString("usernick", usernick);
		mAsyncRunner.request("userscore.do", userparams, "GET",
				new LoadUserScoreRequestListener(), null);
		
		
		
		Bundle ShotListparams = new Bundle();
		ShotListparams.putString("usernickname", usernick);
		mAsyncRunner.request("loaduseractivity.do", ShotListparams, "GET",
				new LoadActivityRequestListener(), null);
		
		/*
		Bundle shotListparams = new Bundle();
     	shotListparams.putString("userid", userid);
     	// db data 가져옴
    	mAsyncRunner.request("loaduseractivity.do", shotListparams, "GET",
                 new LoadActivityRequestListener(), null);
    	//가져온 db data를 controlview에 셋팅
    	activityListView.setAdapter(aa);
    	*/
    	
		/*
		if (userid == null && userid != null) {
			params.putString("userid", userid);
			mAsyncRunner.request("loaduseractivity.do", params, "GET",
					new LoadActivityRequestListener(), null);
		} else {

		}*/
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		// get Tweets ��ư Ŭ��
		case R.id.headerWriteBtn:
			Intent Insert_intent = new Intent(this, AddActivity.class);
			this.startActivity(Insert_intent);
			overridePendingTransition(R.anim.fade, R.anim.hold);
			break;

		case R.id.usernicknameText:
			Intent userHeaderNickintent = new Intent(this,
					UserProfileActivity.class);
			this.startActivity(userHeaderNickintent);
			overridePendingTransition(R.anim.fade, R.anim.hold);
			break;
		case R.id.imgBtnAddFriend:
			AddFriend();

			break;
			
		case R.id.navBtn1:// timeline
			// Intent navBtn2intent = new Intent(this, SearchActivity.class);
			Intent navBtn1intent = new Intent(this, MainActivity.class);
			navBtn1intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			this.startActivity(navBtn1intent);
			overridePendingTransition(R.anim.fade, R.anim.hold);
			finish();
			break;

		case R.id.navBtn2:// stockline
			// Intent navBtn2intent = new Intent(this, SearchActivity.class);
			//Intent navBtn2intent = new Intent(this, SearchActivity.class);
			// navBtn2intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
			// Intent.FLAG_ACTIVITY_SINGLE_TOP);
			//this.startActivity(navBtn2intent);
			//overridePendingTransition(R.anim.fade, R.anim.hold);
			// finish();
			break;

		case R.id.navBtn3:// friendsline
			break;

		case R.id.navBtn4:// profile
			break;

		}
	}

	private void AddFriend() {
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setMessage(usernick + " 님을 친구 추가하시겠습니까?");
		dialog.setPositiveButton("예", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Bundle params = new Bundle();
				params.putString("myNickName", loginnick);
				params.putString("userNickName", usernick);
				mAsyncRunner.request("addfriend.do", params, "POST",
						new AddFriendUserRequestListener(), null);
			}
		});
		dialog.setNegativeButton("취소", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		dialog.show();

	}

	@Override
	public void onCheckedChanged(RadioGroup arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		
	}


	

	public class LoadActivityRequestListener extends BaseRequestListener {
		public void onComplete(final String response, final Object state) {
			Log.d("StockSNS-LoadActivity", "Response: " + response.toString());
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					aa.clear();
					Log.d("StockSNS-LoadActivity",
							"Response: " + response.toString());
					try {
						JSONObject json = Util.parseJson(response);
						if (!json.getString("state").equals("false")) {
							final ArrayList<ShotActivity> shotactivitys = ObjUtils.jsonToShotActivityList(json.getJSONArray("activityList"));
							for (ShotActivity act : shotactivitys) {
								// activityItems.add(act);
								aa.add(act);
							}
							tvHasItem.setVisibility(View.GONE);
							activityListView.setAdapter(aa);
							aa.notifyDataSetChanged();
						} else {
							activityListView.setAdapter(aa);
							aa.notifyDataSetChanged();
							tvHasItem.setVisibility(View.VISIBLE);
							tvHasItem.setText(usernick + " 님이 작성한 액티비티가 없습니다.");
						}

					} catch (JSONException e) {
						Log.w("StockSNS-LoadActivity",
								"JSON Error in response");
					} catch (JustplaceError e) {
						Log.w("StockSNS-LoadActivity",
								"StockSNS Error: " + e.getMessage());
					}
				}
			});

		}
	}

	public class LoadUserScoreRequestListener extends BaseRequestListener {

		public void onComplete(final String response, final Object state) {
			Log.d("StockSNS-LoadUserScore", "Response: " + response.toString());
			try {
				activityItems.clear();
				Log.d("StockSNS-LoadUserScore",
						"Response: " + response.toString());
				JSONObject jsons = Util.parseJson(response);
				JSONObject json = jsons.getJSONObject("userProfile");
				
				
				Log.d("@@@@@@!!@@", json.get("ranking").toString());
				userRanking = json.get("ranking").toString();
				userExp = json.get("score").toString();
				userMayor = json.get("mayorship").toString();
				strUserImg = json.get("profilepic").toString();
				userBio = json.get("bio").toString();
				usernickname = json.get("usernickname").toString();
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						userRankingText.setText(Html
								.fromHtml("<font color='#000000'><b>"
										+ userRanking
										+ "</b></font><br>Ranking"));
						userExpText.setText(Html
								.fromHtml("<font color='#000000'><b>" + userExp
										+ "</b></font><br>Experience"));
						userProfileBioText.setText(userBio);
						userNickText.setText(usernickname);
						//CustomImageManager customImageManager = new CustomImageManager(
						//		mActivity.getApplicationContext(),
						//		R.drawable.defaultuser);
						ImageManager imageManager = new ImageManager(mActivity.getApplicationContext(),
								R.drawable.defaultuser);
						if (strUserImg != null && !strUserImg.equals("null")) {
							userImg.setTag(Justplace.PROFILEIMG_URL + strUserImg);
							//customImageManager.displayPointImage(Justplace.TEST_URL + strUserImg, mActivity, activityUserImg);
							imageManager.displayImage(Justplace.PROFILEIMG_URL + strUserImg, mActivity, userImg);

						} else {
							userImg.setTag(null);
							//customImageManager.displayPointImage(userImg, mActivity,
							//		activityUserImg);
							imageManager.displayImage(strUserImg, mActivity, userImg);
						}
					}

				});

			} catch (JSONException e) {
				Log.w("StockSNS-LoadUserScore", "JSON Error in response");
			} catch (JustplaceError e) {
				Log.w("StockSNS-LoadUserScore",
						"Justplace Error: " + e.getMessage());
			}
		}
	}
	
	
	public class AddFriendUserRequestListener extends BaseRequestListener {

		public void onComplete(final String response, final Object state) {
			try {
				/**
				 * 1. 이미 친구인지 확인 : 친구 추가하려는 유저가 이미 추가되어 있는지 확인하기 위해서 로그인한
				 * 유저의 친구목록을 가져온다
				 **/
				/**
				 * 2. 로그인 user의 친구 목록에 없으므로 대상 user를 친구 추가한다.
				 **/
				isfriend = true;
				Log.d("Justplace-UserProfile-JunstingUser", "Response: " + response.toString());
				JSONObject json = Util.parseJson(response);				
				isfriend = json.getBoolean("isFriend");
				if(isfriend) {
					runOnUiThread(new Runnable() {						
						@Override
						public void run() {
							imgBtnAddFriend.setEnabled(false);
							imgBtnAddFriend.setImageResource(R.drawable.friend_block);
						}
					});
					
				}
				runOnUiThread(new Runnable() {						
					@Override
					public void run() {
						imgBtnAddFriend.setEnabled(false);runOnUiThread(new Runnable() {						
							@Override
							public void run() {
								imgBtnAddFriend.setVisibility(View.VISIBLE);
							}
						});
					}
				});
				/*
				if(isfriend) { // 이미 todolist에 존재
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
					AlertDialog.Builder alert = new AlertDialog.Builder(mActivity);
					alert.setPositiveButton("확인",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(
										DialogInterface dialog,
										int which) {
									dialog.dismiss(); // 닫기
								}
							});
					alert.setMessage("이미 " + userid + " 님이 Justing 되어 있습니다.");
					alert.show();			
						}
					});
				} else { // tolist에 존재하지 않을 때
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
					AlertDialog.Builder alert = new AlertDialog.Builder(mActivity);
					alert.setPositiveButton("확인",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(
										DialogInterface dialog,
										int which) {
									dialog.dismiss(); // 닫기
								}
							});
					alert.setMessage(userid + " 님이 Justing 되었습니다.");
					alert.show();
						}
					});	
				}*/
				Log.d("Justplace-UserProfile-JunstingUser", "isfriend: " + isfriend);
				return;// alertdialog(이미 justing되어 있다는 것을 알려주기 위한)는 activity 안에서만 띄울 수 있다.
			} catch (JSONException e) {
				Log.w("Justplace-FullMain", "JSON Error in response");
			} catch (JustplaceError e) {
				Log.w("Justplace-FullMain", "Justplace Error: " + e.getMessage());
			}
			

		}
	}
}
